package com.hmall.searchService.service;

import com.alibaba.fastjson.JSON;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.searchService.pojo.ItemDoc;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class ItemService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ItemClient itemClient;

    public void insertItemById(Long id) {
        try {
            Item item = itemClient.queryById(id);
            ItemDoc itemDoc = new ItemDoc(item);
            IndexRequest request = new IndexRequest("gouwu").id(itemDoc.getId().toString());
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);

            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void deletedItemById(Long id) {
        try {
            DeleteRequest request = new DeleteRequest("gouwu", id.toString());
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
